#include "widget.h"
#include "ui_widget.h"
#include <QTimer>
#include <QDebug>

double sysActual = 0;
double sysTarget = 0;
double sysInput = 0;

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);


    //创建定时器
    QTimer * timer100 = new QTimer(this);
    QTimer * timer10 = new QTimer(this);

    //定义变量


    //struct pidParameterStruct pid = {};
    //定义“开始运行“按钮功能
    connect(ui->pushButton_Start,&QPushButton::clicked,[=]()
    {
        //启动定时器
        timer100->start(100);//循环周期100ms
        timer10->start(10);//循环周期100ms

        //刷新系统模型和PID控制器，周期10ms
        connect(timer10,&QTimer::timeout,[=](){
            sysInput = controller_PID(sysActual);
            sysActual = Widget::sysModel (sysInput);
        });

        //刷新前端界面
        connect(timer100,&QTimer::timeout,[=](){
            labelTimeShow();
            labelSysActualShow(sysActual);
        });

    });

    //定义“暂停”按钮功能
    //连接“暂停“按钮信号和槽函数
    connect(ui->pushButton_Stop,&QPushButton::clicked,[=]()
    {
        timer100->stop();
        timer10->stop();
    });
}

//函数定义
//显示运行时间
void Widget::labelTimeShow ()
{
    static double num = 1;
    ui->labelTime->setText(QString::number((0.10)*num++));//运行时间递增0.1s
};

//显示系统实际值
void Widget::labelSysActualShow(double sysActual)
{
    ui->labelSysActual->setText(QString::number(sysActual));
};

//系统模型
double Widget::sysModel (double sysInput)
{
    double sysOutput;
    sysOutput = 3*sysInput + 10;
    return sysOutput;
};

//PID控制器
double Widget::controller_PID(double sysOutput)
{
    QString str = ui->editSysTarget->text();
    pid.sysTarget = str.toDouble();

    str = ui->editPID_P->text();
    pid.PID_P = str.toDouble();
    str = ui->editPID_I->text();
    pid.PID_I = str.toDouble();
    str = ui->editPID_D->text();
    pid.PID_D = str.toDouble();

    pid.error = pid.sysTarget - sysOutput;
    pid.integral+= pid.error;
    pid.PID_Output = pid.PID_P*pid.error + pid.PID_I*pid.integral + pid.PID_D*(pid.error - pid.errorLast);
    pid.errorLast = pid.error;

    return pid.PID_Output;


};

Widget::~Widget()
{
    delete ui;
}


